/**
 * 一体化业务控制台科技有限公司
 */
var URL_PARAM, LAST_PARAM, LAST_PARAMS;

var BASE_URL = "";
var WEB_URL = "";

//当前模块ID
var MODULE_ID = 0;
var ROLE_TYPE = 0;
var IFRAME_TOP = [];
var IFRAME_W_H = [0, 0];

/** 类型字符串常量 */
var TYPE = { FUN: "function", ARR: "[object Array]", OBJ: "[object Object]", STRING: "string" };

var handle_flag = 1;

var TypeCheck = {
    /** 类型检测 */
    isObject: function(o) {
        return o.valueOf().toString() === TYPE.OBJ;
    },
    isString: function(o) {
        return typeof o === TYPE.STRING;
    },
    isFunction: function(o) {
        return typeof o === TYPE.FUN;
    },
    isArray: Array.isArray || function(o) {
        return Object.prototype.toString.call(o) === TYPE.ARR;
    }
};

/**
 * ajax请求
 * 调用示例
 * This.ajax(Api.face_contrast, {p:1}, function(data) {
		alert(data.message)
	});
 */
var This = {
    ajax: function (apiName, params, fn, async) {
        var url = BASE_URL + apiName;
        url += "?data=" + JSON.stringify(params);
        Ajax.xhr(url, fn, async);
    },
    jqueryAjax: function(apiName, params, dataType, fn, async, accept, contentType) {
    	var _async = async || "";
        var retData;
        params = params || {};

        var _params = {};

        if (params) {
            if (TypeCheck.isObject(params)) {
                for (var key in params) {
                    var val = params[key];
                    if (typeof val == 'string' && val.constructor == String) {
                        val = val.replace(/&quot;/g, "_quot;");
                        val = val.replace(/&nbsp;/g, "_nbsp;");
                    }
                    _params[key] = val;
                }
            }
        }

        $.extend(_params, {t: new Date().getTime()});

        jQuery.ajax({
            type: 'post',
            dataType: dataType || 'json',
            url: apiName,
            async: _async == true ? true : false,
            data: _params,
            cache: false,
            success: function(data) {
                if (data && data.status && data.status == 403) {
                    location.href = "/";
                    return false;
                }
                retData = data;
                if (_async) {
                    return fn.call('', retData);
                }
            }, error: function(data) {
                if (data.status == 403) {
                    location.href = "/";
                }
                //location.href = "/";
            }
        });

        if (!_async) {
            if (fn) {
                return fn.call('', retData);
            }
            return retData;
        }
    },
};

var Ajax = {
    xhr: function(url, fn, async) {
        var xhr = Ajax.getHttpObj();
        xhr.open("POST", url, async || true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    var response = xhr.responseText;
                    response = response.replace(/\\\u00b7/g, "·").replace(/\\\uff0c/g, "，");
                    response = eval('(' + response + ')');
                    return fn.call(xhr, response);
                } else {
                    // 错误处理
                    var data = {};
                    data["status"] = "0";
                    data["message"] = "数据请求错误";
                    return fn.call(xhr, data);
                }
            }
        };

        xhr.send();
    },
    getHttpObj: function() {
        var httpobj = null;
        try {
            httpobj = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                httpobj = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e1) {
                httpobj = new XMLHttpRequest();
            }
        }
        return httpobj;
    }
};

var Url = {
    /** 获取路径参数 */
    initUrlParams: function (url) {
        var params = {},
            paramsStr = "",
            paramsArr = [];

        var arr = url.split("?");
        if (arr.length > 2) {
            var paramArr1 = arr[1].split("&");
            var paramArr2 = arr[2].split("&");

            for (var i = 0; i < paramArr1.length; i++) {
                var param = paramArr1[i] ? paramArr1[i].split("=") : undefined;
                if (param) params[param[0]] = param[1];
            }

            for (var i = 0; i < paramArr2.length; i++) {
                var param = paramArr2[i] ? paramArr2[i].split("=") : undefined;
                if (param) params[param[0]] = param[1];
            }

            return params;
        } else {
            paramsStr = url.split("?")[1];
            paramsArr = paramsStr ? paramsStr.split("&") : [];

            for (var i = 0; i < paramsArr.length; i++) {
                // ?& 当路劲中存在这样的情况的时候会出现空数组
                // TODO 含有 # 号的情况
                var param = paramsArr[i] ? paramsArr[i].split("=") : undefined;
                if (param) params[param[0]] = param[1];
            }

            return params;
        }
    },
    creatUrl: function(name, params, is_new, title) {
        var name = name || Api.baseModule.url;

        var urlPath = name;
        var paramArr = [];
        var url;

        if (params) {
            if (TypeCheck.isObject(params)) {
                for (var key in params) {
                    var param = [key, encodeURIComponent(decodeURIComponent(params[key]))].join("=");
                    paramArr.push(param);
                }
                paramStr = paramArr.join("&");
            } else {
                paramStr = params;
            }
        }

        if (params && paramStr) {
            url = [urlPath, paramArr.join("&")].join("?");
        } else {
            url = urlPath;
        }
        if (is_new) {
            return "popup(" + url + "," + title + ")";
        }
        if (url.indexOf("?") != -1) {
            return url + "&t=" + new Date().getTime();
        }
        return url + "?t=" + new Date().getTime();
    },
    /** 获取路径参数 */
    initUrl: function (url) {
        if (!url) {
            url = location.pathname;
        }
        url = url.substr(url.lastIndexOf("/") + 1, url.length);
        LAST_PARAMS = url.split("_");
        return url;
    }
};

var Layui = {
    confirm: function (message, option, fn, save) {
        layer.confirm(message, option || {
            shade: 0.2,
            btn: ['确定', '取消']
        }, function(index, layero, content) {
            if (content && typeof content == "string" && content.indexOf('noCloseLayer') != -1) {
                setTimeout(function() {
                    return fn.call(layero, index);
                }, 50);
            } else {
                layer.close(index);
                if (!(save && save === "0")) {
                    noSubmit();
                }
                setTimeout(function() {
                    return fn.call(layero, index);
                }, 50);
                setTimeout(function() {
                    reSubmit();
                }, 3000);
            }
        });
    },
    confirmLoad: function (message, option, fn) {
        layer.confirm(message, option || {
            shade: 0.2,
            btn: ['确定', '取消']
        }, function(index, layero, content) {
            layer.close(index);
            _loading();
            setTimeout(function() {
                return fn.call(layer, index);
            }, 50);
            setTimeout(function() {
                _loadingClose();
            }, 3000);
        });
    },
    open: function (option) {
        layer.open(option);
    },
    prompt: function (option) {
        layer.prompt(option);
    },
};

var MyDate = {
    week: function () {
        var a = new Array("日", "一", "二", "三", "四", "五", "六");
        var week = new Date().getDay();
        return "星期" + a[week];
    },
    day: function () {
        var date = new Date();
        return date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日";
    }
};

var RegExpL = {
    required: /[\S]+/,
    phone: /^1\d{10}$/,
    email: /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/,
    url: /(^#)|(^http(s*):\/\/[^\s]+\.[^\s]+)/,
    float: /^(:?(:?\d+.\d+)|(:?\d+))$/,
    date: /^(\d{4})[-\/](\d{1}|0\d{1}|1[0-2])([-\/](\d{1}|0\d{1}|[1-2][0-9]|3[0-1]))*$/,
    identity: /(^\d{15}$)|(^\d{17}(x|X|\d)$)/,
    postalCode: /^[0-9]{6}$/,
    number: /^\d{1,}$/,    /*  /^\+?[1-9][0-9]*$/ 验证非零的正整数  */
    check: {
        is_number: function(value) {
            var patrn = RegExpL.number;
            if (patrn.exec(value) == null || value == "") {
                return false;
            } else {
                return true;
            }
        },
        isDouble : function(value){
            if (value.match(/^(:?(:?\d+.\d+)|(:?\d+))$/)) {
                return true ;
            } else {
                return false;
            }
        }
    },
    // 不校验空
    checkVal : {
        c_url : function (value, item){
            if(value && !RegExpL.url.test(value)){
                return '网址格式不正确，格式如：https://www.***.com';
            }
        },
        c_postalCode : function (value, item){
            if(value && !RegExpL.postalCode.test(value)){
                return '邮政编码格式不正确';
            }
        },
        isCardID : function (value, item){
            if(value){
                return isCardIDCheck(value);
            }
        },
    }
}

/**
 * 输入数字验证
 * @param verify
 */
function verifyNumber(_this) {
    var val = $(_this).val();
    if(val && !RegExpL.check.is_number(val)){
        $(_this).val("");
        $(_this).focus();
        layerMessage("必须为数字", 5, 1);
    }
}

/**
 * 输入数字验证
 * @param verify
 */
function verifyFloat(_this, maxValue) {
    var val = $(_this).val();
    if (maxValue && Number(val) > maxValue) {
        $(_this).val("");
        $(_this).focus();
        layerMessage("最大值不能超过" + maxValue, 5, 1);
    }
    if(val && !RegExpL.check.isDouble(val)){
        $(_this).val("");
        $(_this).focus();
        layerMessage("必须为浮点型数字", 5, 1);
    }
}

/** 页面参数 */
URL_PARAM = Url.initUrlParams(location.search);
LAST_PARAM = Url.initUrl(location.pathname);


/* 获取Checkbox选中值 */
function getCheckboxVal (name){
    var vals = '';
    $("input[name='"+name+"']:checked").each(function (){
        vals += $(this).val() + ',';
    });
    return vals.substring(0,vals.length-1);
}